package kr.saeildamil.androidStudy_second.gesture;

import java.util.ArrayList;

import kr.saeildamil.androidStudy_second.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.TextView;

public class TouchDump extends Activity {
	ArrayList<String> arTouch;
	TextView mResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch31_touchdump);

		arTouch = new ArrayList<String>();

		mResult = (TextView) findViewById(R.id.result);
		mResult.setText("멀티터치를 테스트");
	}

	final static String[] arAction = { "DOWN", "UP", "MOVE", "CANCEL",
			"OUTSIDE", "PDOWN", "PUP" };

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		int pureaction = action & MotionEvent.ACTION_MASK;
		@SuppressWarnings("deprecation")
		int pid = (action & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;

		String info = ("p" + pid + " " + arAction[pureaction]);

		for (int i = 0; i < event.getPointerCount(); i++) {
			info += (String.format("p%d (%d, %d)", event.getPointerId(i),
					event.getX(i), event.getY(i)));
		}

		if (event.getPointerCount() > 1) {
			int dx = (int) (event.getX(0) - event.getX(1));
			int dy = (int) (event.getY(0) - event.getY(1));
			int distance = (int) (Math.sqrt(dx * dx + dy * dy));
			info += " dis=" + distance;
		}

		appendText(info.toString());

		return true;

	}

	private void appendText(String text) {
		if (arTouch.size() > 15) {
			arTouch.remove(0);
		}
		arTouch.add(text);
		StringBuilder result = new StringBuilder();
		for (String s : arTouch) {
			result.append(s);
			result.append("\n");
		}
		mResult.setText(result.toString());
	}
}
